package com.itshare.video.aop;

import com.itshare.video.common.aop.AopUtils;
import com.itshare.video.common.core.constant.enums.ApiInfo;
import com.itshare.video.common.dto.Result;
import com.itshare.video.common.dto.ViewObject;
import com.itshare.video.common.exception.ServiceException;
import com.itshare.video.common.web.WebUtil;
import com.itshare.video.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 拦截用户上传 API
 * @Author lyr
 * @create 2020/11/2 16:55
 */
@Slf4j
@Aspect
@Component
@Lazy
public class AccountAspect {

    @Pointcut("@annotation(com.itshare.video.aop.annontations.AccountFreezeCheck)")
    public void accountDelegate() {
        // log.info("args-> {}", Arrays.toString(pjp.getArgs()));
    }

    @Resource
    private UserService userService;

    @Around(value = "accountDelegate()")
    public Object xxx(ProceedingJoinPoint pj) {
        try {
            HttpServletRequest request = WebUtil.getRequest();

            Integer id = (Integer.valueOf(request.getAttribute("id").toString())) ;

            if(userService.isUserAccountFreeze(id)) {
                //如果用户被举报，封号
                Class<?> clazz = AopUtils.getAopMethod(pj).getReturnType();
                // Long ttl = userService.getTTLOfAccountFreeze(id);
                if (ViewObject.class.isAssignableFrom(clazz)) {
                    //view object 类型
                    return ViewObject.ofCode(ApiInfo.ACCOUNT_FREEZE)
                            .setMessage("用户账号冻结，暂时无法使用api");
                }else if (Result.class.isAssignableFrom(clazz)) {

                    //result 类型
                    return Result.ofCode(ApiInfo.ACCOUNT_FREEZE)
                            .setMessage("用户账户冻结，暂时无法使用 API");
                }else {
                    //接口运行异常
                    throw new ServiceException(ApiInfo.BASIC_ERROR);
                }
            }

            return pj.proceed(pj.getArgs());

        } catch (Throwable throwable) {
            throw new RuntimeException(throwable);
        }

    }
}
